import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import '../widget/commit/my_appbar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

// Drawer小部件
import '../widget/drawer/drawer.dart';
import '../widget/home/msglist.dart'; // 消息列表
import '../widget/home/userlist.dart';  // 用户列表
import '../widget/home/statistics.dart';  // 数据统计


import '../model/my_store.dart';
import '../model/config.dart';

class HomePage extends StatefulWidget {
  HomePage({
    Key key,
    this.setTheme
  }):super(key: key);
  dynamic setTheme;
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool drawerIsOpen = false; // 侧边抽屉的打开状态
  bool brightnessColor; // 状态栏背景是否是白色
  Map csuser; // 客服信息
  List<Map> _pageviewList = [];
  String _title;
  SwiperController swiperController;
  int pageIndex;
  @override
  void initState () {
    csuser = getCsUser();
    print(csuser);
    _pageviewList
    ..add({
      'title': '消  息',
      'item': MsgList(
        csid: csuser['id'],
      )
    })
    ..add({
      'title': '用  户',
      'item': UserList(
        csid: csuser['id'],
      )
    })
    ..add({
      'title': '统  计',
      'item': Statistics(
        csid: csuser['id'],
      )
    });
    pageIndex = 0;
    _title = _pageviewList[0]['title'];
    swiperController = SwiperController();
    super.initState();
    brightnessColor = true;
  }
  Map getCsUser () { // 从本地缓存回去用户信息
    var logininfo = MyStore().getData('LOGININFO');
    return MyStore().getData('CSUSER${logininfo['id']}');
  }

  setPageTitle (String title) { // 从本地缓存回去用户信息
    setState(() {
      _title = title;
    });
  }

  refreshCsuser (int csid) async { // 刷新客服信息，返回最新信息
    var response = await Dio().get(
      MyConfig().baseurl + '/csuser/getcsuser',
      data: {
        'id' : csid
      }
    );
    var newCsuser;
    if (response.statusCode == 200 && response.data['status'] == 1) {
      newCsuser = response.data['cs_info'];
    } else {
      newCsuser = null;
    }
    if (newCsuser != null) {
      MyStore().setData('CSUSER${csid}', newCsuser);
      setState(() {
        csuser['nickname'] = newCsuser['nickname'];
        csuser['type'] = newCsuser['type'];
        csuser['status'] = newCsuser['status'];
        csuser['username']  = newCsuser['username'];
        csuser['header_url'] = newCsuser['header_url'];
      });
    }
    return newCsuser;
  }
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _onBackPressed,
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: PreferredSize(
          child: MyAppBar(
            brightness: brightnessColor,
            title: _title,
            leading: buttonInfo(
              icon: 0xe7f4,
             type: 'openDrawer'
            ),
          ),
          preferredSize: Size.fromHeight(ScreenUtil().setWidth(80)),
        ),
        drawer: MyDrawer(
          openCallback: (isOpen) {
            drawerIsOpen = isOpen;
          },
          setTheme:widget.setTheme,
          csuser: csuser,
          onRefresh: refreshCsuser
        ),
        body: Column(
          children: <Widget>[
            Expanded(
              child: Swiper(
                viewportFraction: 0.99999,
                controller: swiperController,
                itemBuilder: (BuildContext context,int index) {
                  return _pageviewList[index]['item'];
                },
                itemCount: 3,
                loop: false,
                onIndexChanged: (int index) {
                  setState(() {
                    pageIndex = index;
                    _title = _pageviewList[index]['title'];
                  });
                }
              ),
            ),
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: Border(
                  top: BorderSide(
                    width: 1,
                    color: Color.fromRGBO(223, 223, 223, 1)
                  )
                )
              ),
              height: ScreenUtil().setWidth(120),
              child: Row(
                children: <Widget>[
                  Expanded(
                    child: InkWell(
                      onTap: () {
                        swiperController.move(0);
                      },
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Icon(
                            IconData(0xe610, fontFamily: 'iconfont'),
                            color: pageIndex == 0 ? Theme.of(context).primaryColor : Theme.of(context).disabledColor,
                          ),
                          Text(
                            '消息',
                            style: TextStyle(
                              color: pageIndex == 0 ? Theme.of(context).primaryColor : Theme.of(context).disabledColor,
                              fontSize: ScreenUtil().setWidth(24)
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    child: InkWell(
                      onTap: () {
                        swiperController.move(1);
                      },
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Icon(
                            IconData(0xe851, fontFamily: 'iconfont'),
                            color: pageIndex == 1 ? Theme.of(context).primaryColor : Theme.of(context).disabledColor,
                          ),
                          Text(
                            '用户',
                            style: TextStyle(
                              color: pageIndex == 1 ? Theme.of(context).primaryColor : Theme.of(context).disabledColor,
                              fontSize: ScreenUtil().setWidth(24)
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    child: InkWell(
                      onTap: () {
                        swiperController.move(2);
                      },
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: <Widget>[
                          Icon(
                            IconData(0xe64e, fontFamily: 'iconfont'),
                            color: pageIndex == 2 ? Theme.of(context).primaryColor : Theme.of(context).disabledColor,
                          ),
                          Text(
                            '统计',
                            style: TextStyle(
                              color: pageIndex == 2 ? Theme.of(context).primaryColor : Theme.of(context).disabledColor,
                              fontSize: ScreenUtil().setWidth(24)
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
  Future<bool> _onBackPressed() { // 返回函数
    if (drawerIsOpen) {
      Navigator.pop(context, true);
      return null;
    }
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text('是否退出应用！'),
          actions: <Widget>[
            FlatButton(
              child: Text('否'),
              onPressed: () => Navigator.pop(context, false),
            ),
            FlatButton(
              child: Text('是'),
              onPressed: () => Navigator.pop(context, true),
            ),
          ],
        );
      }
    );
  }
}